package com.isczy.educms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.isczy.educms.service.MsmService;
import com.isczy.educms.utils.YamlConstant;
import com.isczy.servicebase.exceptionHandler.MyException;
import com.isczy.utils.ResultCode;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {

    /***
     * ***************************************
     * 功能描述:发送短信
     * @param param
     * @param phone
     * @return {@link boolean}
     * @author create: TODO 人员:【ChangZiYang】类型:【新增方法】日期:【2021-01-14 15:03】
     * @author modify:
     */
    @Override
    public boolean send(Map<String, Object> param, String phone) {

        DefaultProfile profile = DefaultProfile
                .getProfile("default", YamlConstant.ACCESS_KEY_ID, YamlConstant.ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        //设置相关固定的参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //设置发送相关的参数
        request.putQueryParameter("PhoneNumbers",phone); //手机号
        request.putQueryParameter("SignName","我的谷粒在线教育网站"); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode","SMS_209566118"); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //验证码数据，转换json数据传递

        try {
            //最终发送
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            return success;
        }catch(Exception e) {
            throw MyException.builder()
                    .exception(e)
                    .code(ResultCode.ERROR)
                    .className(getClass().getName())
                    .methodName(Thread.currentThread().getStackTrace()[1].getMethodName())
                    .message("发送失败")
                    .params(phone)
                    .build();
        }

    }
}
